package org.fer.practico6;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Practico6Activity extends Activity {
	/** Called when the activity is first created. */

	private TextView tvx;
	private TextView tvy;

	@Override
	public void onStart() {
		super.onStart();

		this.findViewById(R.id.main_id).setOnLongClickListener(
				new OnLongClickListener() {

					@Override
					public boolean onLongClick(View v) {
						RelativeLayout rl = (RelativeLayout) v;
						rl.removeAllViews();
						rl.addView(tvx);
						rl.addView(tvy);
						return false;
					}
				});

		this.findViewById(R.id.main_id).setOnTouchListener(
				new OnTouchListener() {

					@Override
					public boolean onTouch(View v, MotionEvent me) {

						if (me.getAction() == MotionEvent.ACTION_DOWN) {
							String sX = getResources()
									.getString(R.string.pos_x);
							String sY = getResources()
									.getString(R.string.pos_y);
							float x = me.getX();
							float y = me.getY();

							tvx.setText(String.format(sX, String.valueOf(x)));
							tvy.setText(String.format(sY, String.valueOf(y)));

							RelativeLayout mainLay = (RelativeLayout) findViewById(R.id.main_id);

							ImageView icono = new ImageView(
									Practico6Activity.this);
							icono.setImageDrawable(getResources().getDrawable(
									R.drawable.ic_launcher));

							RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
									LayoutParams.WRAP_CONTENT,
									LayoutParams.WRAP_CONTENT);

							int xCentrado = (int) x
									- (icono.getMeasuredWidth() / 2);
							int yCentrado = (int) y
									- (icono.getMeasuredHeight() / 2);

							lp.setMargins(xCentrado, yCentrado, 0, 0);

							icono.setLayoutParams(lp);
							mainLay.addView(icono);

						}

						return false;
					}
				});
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		tvx = (TextView) findViewById(R.id.textView1);
		tvy = (TextView) findViewById(R.id.textView2);
	}
}